using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
using System.Drawing;
using System.Text;

using Styx;
using Styx.CommonBot;
using Styx.CommonBot.Routines;
using Styx.Helpers;
using Styx.TreeSharp;
using Styx.WoWInternals;
using Styx.WoWInternals.WoWObjects;
using Styx.Common.Helpers;
using Styx.Pathing;

using CommonBehaviors.Actions;

using Singular.Dynamics;
using Singular.Helpers;
using Singular.Managers;
using Singular.Settings;

using Action = Styx.TreeSharp.Action;
//
using Rest = Singular.Helpers.Rest;
//
using LocationRetriever = Singular.Helpers.LocationRetriever;

namespace Beary
{
    public class Routine : CombatRoutine
    {
        /// <summary>
        /// The name of this CombatRoutine
        /// </summary>
        /// <value>
        /// The name.
        /// </value>
        public override string Name { get { return "Bear1.0"; } }


        /// <summary>
        /// The <see cref="T:Styx.WoWClass"/> to be used with this routine
        /// </summary>
        /// <value>
        /// The class.
        /// </value>
        public override WoWClass Class { get { return WoWClass.Druid; } }


        private Composite _combat, _buffs;


        public override Composite CombatBehavior { get { return _combat; } }
        public override Composite PreCombatBuffBehavior { get { return _buffs; } }
        public override Composite CombatBuffBehavior { get { return _buffs; } }

		private bool IsTargetBoss()
        {
            if (StyxWoW.Me.CurrentTarget.CreatureRank == WoWUnitClassificationType.WorldBoss ||
               (StyxWoW.Me.CurrentTarget.Level >= 90 && StyxWoW.Me.CurrentTarget.Elite && StyxWoW.Me.CurrentTarget.MaxHealth > 6000000))
                return true;

            else return false;
        }
		
		private int addCount()
        {
            int count = 0;
            foreach (WoWUnit u in ObjectManager.GetObjectsOfType<WoWUnit>(true, true))
            {
                if (u.IsAlive
                    && StyxWoW.Me.CurrentTarget != null
                    && u.Guid != StyxWoW.Me.Guid
                    && !u.IsFriendly
                    && (u.IsHostile || u.IsNeutral)
                    && !u.IsCritter
                    && u.Location.Distance(StyxWoW.Me.Location) <= 8
                    && (u.IsTargetingMyPartyMember || u.IsTargetingMyRaidMember || u.IsTargetingMeOrPet || u.IsTargetingAnyMinion))
                {
                    count++;
                }
            }
            return count;
        }

		private int HSaddCount()
        {
            int count = 0;
            foreach (WoWUnit u in ObjectManager.GetObjectsOfType<WoWUnit>(true, true))
            {
                if (u.IsAlive
                    && StyxWoW.Me.CurrentTarget != null
                    && u.Guid != StyxWoW.Me.Guid
                    && !u.IsFriendly
                    && (u.IsHostile || u.IsNeutral)
                    && !u.IsCritter
                    && u.IsWithinMeleeRange
                    && (u.IsTargetingMyPartyMember || u.IsTargetingMyRaidMember || u.IsTargetingMeOrPet || u.IsTargetingAnyMinion))
                {
                    count++;
                }
            }
            return count;
        }

        public override void Initialize()
        {
            _combat = CreateCombat();
            _buffs = CreateBuffs();
        }


        Composite CreateBuffs()
        {
            return new PrioritySelector(
				//Cast("Bear Form", ret => !StyxWoW.Me.HasAura("Bear Form") && !StyxWoW.Me.Mounted),
				Cast("Nature's Swiftness", ret => !StyxWoW.Me.Mounted && !StyxWoW.Me.ActiveAuras.Any(u => u.Key == "Nature's Swiftness")), //&& !StyxWoW.Me.HasAura("Bear Form") ),
				Cast("Mark of the Wild", ret => (!StyxWoW.Me.HasAura("Mark of the Wild") && !StyxWoW.Me.Mounted)),
				Cast("Bone Shield", ret => (!StyxWoW.Me.HasAura("Bone Shield") && !StyxWoW.Me.Mounted)),
				new Decorator(ret =>
					!StyxWoW.Me.HasAura("Visions of Insanity"),
					new Action(abc =>
					{
						WoWItem item = StyxWoW.Me.BagItems.Find(ret => ret.Entry == 86569);
                            if (item != null) item.Use(); 
					}))
				//Cast("Crystal of Insanity", ret => (!StyxWoW.Me.HasAura("Visions of Insanity") && !StyxWoW.Me.Mounted))
			);
        }


        Composite CreateCombat()
        {
			return new Decorator ( ctz => !StyxWoW.Me.Mounted && !StyxWoW.Me.HasAura("Drink") && !StyxWoW.Me.HasAura("Food") && !StyxWoW.Me.HasAura("First Aid"),
				new PrioritySelector(


                // Interrupt please.
                Cast("Skull Bash", ret => StyxWoW.Me.CurrentTarget.IsCasting && StyxWoW.Me.CurrentTarget.CanInterruptCurrentSpellCast),
                Cast("Mighty Bash", ret => StyxWoW.Me.CurrentTarget.IsCasting && StyxWoW.Me.CurrentTarget.CanInterruptCurrentSpellCast && SpellManager.Spells["Skull Bash"].Cooldown),
                Cast("War Stomp", ret => StyxWoW.Me.CurrentTarget.IsCasting && StyxWoW.Me.CurrentTarget.CanInterruptCurrentSpellCast && SpellManager.Spells["Skull Bash"].Cooldown && SpellManager.Spells["Mighty Bash"].Cooldown),
                Cast("Disorienting Roar", ret => StyxWoW.Me.CurrentTarget.IsCasting && StyxWoW.Me.CurrentTarget.CanInterruptCurrentSpellCast && SpellManager.Spells["Skull Bash"].Cooldown && SpellManager.Spells["Mighty Bash"].Cooldown),

				// Defensive/Healing CD
				Cast("Nature's Swiftness", ret => !StyxWoW.Me.ActiveAuras.Any(u => u.Key == "Nature's Swiftness")),
				Cast("Enrage", ret => StyxWoW.Me.RagePercent < 40),
				Cast("Bone Shield", ret => !StyxWoW.Me.HasAura("Bone Shield")),
				Cast("Feint", ret => StyxWoW.Me.HealthPercent < 75),
				Cast("Elusive Brew", ret => StyxWoW.Me.HealthPercent < 75),
				Cast("Healing Touch", ret => StyxWoW.Me.HealthPercent < 75 && StyxWoW.Me.ActiveAuras.Any(u => u.Key == "Nature's Swiftness")),
				//Cast("Frenzied Regeneration", ret => StyxWoW.Me.HealthPercent <= 80 && StyxWoW.Me.CurrentRage >= 60 && !StyxWoW.Me.HasAura("Frenzied Regeneration")),
				Cast("Renewal", ret => StyxWoW.Me.HealthPercent <= 70),
				Cast("Savage Defense", ret => !StyxWoW.Me.HasAura("Savage Defense")),
				Cast("Barkskin", ret => StyxWoW.Me.HealthPercent < 90),
				Cast("Might of Ursoc", ret => StyxWoW.Me.HealthPercent < 45),
				Cast("Survival Instinct", ret => StyxWoW.Me.HealthPercent < 55),
				//Cast("Anti-Magic Shell", ret => !StyxWoW.Me.HasAura("Anti-Magic Zone") && StyxWoW.Me.HealthPercent < 70),
				//Spell.CastOnGround("Light's Hammer", ctx => StyxWoW.Me.Location, ret => StyxWoW.Me.HealthPercent < 75),
				Cast("Incarnation: Son of Ursoc", ret => StyxWoW.Me.ActiveAuras.Any(u => u.Key == "Berserk")),
				Cast("Incarnation: Son of Ursoc", ret => StyxWoW.Me.HasAura("Berserk")),
				Cast("Incarnation: Son of Ursoc", ret => IsTargetBoss() || addCount() > 5 || StyxWoW.Me.ActiveAuras.Any(u => u.Key == "Bloodlust") ||
					StyxWoW.Me.ActiveAuras.Any(u => u.Key == "Bloodlust") || StyxWoW.Me.ActiveAuras.Any(u => u.Key == "Time Warp")),

				Cast("Faerie Fire", ret=> !StyxWoW.Me.CurrentTarget.HasAura("Weakened Armor")),
				//AOE ================
				new Decorator( ret => addCount() > 1,
					new PrioritySelector(
						Cast("Incarnation: Son of Ursoc", ret => StyxWoW.Me.ActiveAuras.Any(u => u.Key == "Berserk")),
						Cast("Thrash"),
						Cast("Swipe"),
						Cast("Consecration"),
						Cast("Mangle", ret => StyxWoW.Me.ActiveAuras.Any(u => u.Key == "Berserk")),
						//Cast("Blood Boil", ret=> StyxWoW.Me.Buffs.ContainsKey("Crimson Scourge") ||//),
						//	Me.HasActiveAura("Crimson Scourge") || StyxWoW.Me.HasAura(81141)),
						Cast("Maul", ret => StyxWoW.Me.ActiveAuras.Any(u => u.Key == "Tooth and Claw")),
						//Spell.CastOnGround("Death and Decay", ret => StyxWoW.Me.CurrentTarget.Location, ret => addCount() > 2),
						Cast("Mangle")
					)
				), //&& StyxWoW.Me.HasAura("Crimson Scourge")),
				//Cast("Heart Strike", ret => StyxWoW.Me.BloodRuneCount > 0 || HSaddCount() == 2),
				// ===================
						Cast("Mangle"),
						Cast("Thrash"),
						Cast("Lacerate"),
						//Cast("Blood Boil", ret=> StyxWoW.Me.Buffs.ContainsKey("Crimson Scourge") ||//),
						//	Me.HasActiveAura("Crimson Scourge") || StyxWoW.Me.HasAura(81141)),
						Cast("Maul", ret => StyxWoW.Me.ActiveAuras.Any(u => u.Key == "Tooth and Claw")),
						//Spell.CastOnGround("Death and Decay", ret => StyxWoW.Me.CurrentTarget.Location, ret => addCount() > 2),
						Cast("Faerie Fire")
			));
        }

        void UseTrinkets()
        {
            var firstTrinket = StyxWoW.Me.Inventory.Equipped.Trinket1;
            var secondTrinket = StyxWoW.Me.Inventory.Equipped.Trinket2;


            if(firstTrinket != null && CanUseEquippedItem(firstTrinket))
                firstTrinket.Use();


            if(secondTrinket != null && CanUseEquippedItem(secondTrinket))
                secondTrinket.Use();


        }
        private static bool CanUseEquippedItem(WoWItem item)
        {
            // Check for engineering tinkers!
            string itemSpell = Lua.GetReturnVal<string>("return GetItemSpell(" + item.Entry + ")", 0);
            if (string.IsNullOrEmpty(itemSpell))
                return false;


            return item.Usable && item.Cooldown <= 0;
        }


        IEnumerable<WoWUnit> UnfriendlyUnits
        {
            get { return ObjectManager.GetObjectsOfType<WoWUnit>(true, false).Where(u => !u.IsDead && u.CanSelect && u.Attackable && !u.IsFriendly && u.IsWithinMeleeRange); }
        }

        private delegate T Selection<out T>(object context);
        Composite Cast(string spell, Selection<bool> reqs = null)
        {
            return
                new Decorator(
                    ret => ((reqs != null && reqs(ret)) || (reqs == null)) && SpellManager.CanCast(spell),
                    new Action(ret => SpellManager.Cast(spell)));
        }


        public static TimeSpan GetSpellCooldown(string spell)
        {
            SpellFindResults results;
            if (SpellManager.FindSpell(spell, out results))
            {
                if (results.Override != null)
                    return results.Override.CooldownTimeLeft;
                return results.Original.CooldownTimeLeft;
            }


            return TimeSpan.MaxValue;
        }
    }
}